package com.sudoku.SudokuV01;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.*;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.sudokuModel.grilleModele;
import com.sudokuModel.sudokuCase;

import java.util.LinkedList;

/**
 * Created by richard on 31/01/14.
 */


public class Dessin extends View  implements View.OnTouchListener {
    boolean  isRunning;
    changementClock clock;
    int viewWidth;
    int viewHeight;
    grilleModele maGrille;
    public long time=0;
    public Handler handler;

    public Dessin(Context context) {
        super(context);

    }
    public Dessin(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnTouchListener(this);

        maGrille = new grilleModele();
        maGrille.setTestGrille();
       // Log.e("MY MESS3 " ,g.getDescription());
    }
    @Override
    public void onDraw(Canvas canvas) {


        // ADD to get View size
        Paint paint = new Paint();
        //canvas.drawPaint(paint);
        viewWidth = this.getWidth();
        viewHeight = this.getHeight();

        paint.setColor(Color.WHITE);
        paint.setTextSize(32);
      //  canvas.drawText(viewWidth + " -- " + viewHeight, 20, 40, paint);
        this.drawGrille(canvas);
       // this.drawMaskNumber(canvas);
        this.drawNumber(canvas);
        this.drawMenu(canvas);
        this.drawClock(canvas);
       //
    }
/*
    Draw clock our le decompte du temps
*/


    private int determineMaxTextSize(String str, float maxWidth)
    {
        int size = 0;
        Paint paint = new Paint();

        do {
            paint.setTextSize(++ size);
        } while(paint.measureText(str) < maxWidth);

        return size;
    } //End getMaxTextSize()


    private void drawClock(Canvas canvas) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
        paint.setTextSize(72);
        int x = 0;
        int y =  viewWidth + ((viewWidth/9 )* 2);
        paint.setStyle(Paint.Style.FILL);

        paint.setColor(Color.GREEN);
        int se = (int)(this.time / 1000);
        int m = se/60;
        se = se- (m*60) ;
        String clk = m +":" +se;
        canvas.drawText(clk,x +(viewWidth/3), y + 55, paint);
    }
/*
draw menu de saisie des chiffres
 */


    private void drawMenu(Canvas canvas) {
        Paint paint = new Paint();
        paint.setTextSize(48);
        int x = 0;
        int y =  viewWidth + 10;

        RectF r = new RectF (x , y ,x +viewWidth/9,y + viewWidth/9);


        for (int i = 0 ; i <9 ; i ++ ){


            paint.setColor(Color.BLACK);
            r = new RectF (x , y ,x +viewWidth/9,y + viewWidth/9);
            canvas.drawRect(r,paint);
            r = new RectF (x +2, y +2, (x -2)  +viewWidth/9,(y - 2)  + viewWidth/9);
            paint.setColor(Color.LTGRAY);

            canvas.drawRoundRect( r,(float) 0.2,(float)0.6, paint);
            paint.setColor(Color.BLACK);

            canvas.drawText(""+(i+1),x +30 , y + 55, paint);
            x = x + ( viewWidth/9);

        }

    }


    /*
    draw number  permet de dessiner le numero choisit avec un filtre de fond si nécessaire
     */
    private void drawNumber(Canvas canvas) {
        float c0 = viewWidth /9;
        float l0 = viewWidth /9;
        int cpt=0;
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
        paint.setColor(Color.BLACK);
        paint.setTextSize(48);

        Typeface tf = Typeface.create("fontf1.ttf",Typeface.BOLD);
        paint.setTypeface(tf);

       /* for (int l= 0 ; l < 9 ; l++) {

            for (int k= 0 ; k < 9 ; k++) {

                float c1 = (viewWidth/9) *k;
                float l1 = (viewWidth /9) *l;
                float x = (((float)(c0)) / 3 )+ 0 +c1;
                float y = (((float)(l0)) / 3 )+ 25 + l1;

                if (this.maGrille.listeCases[(k*l)+k].value !=0 ) {
                        paint.setColor(Color.BLUE);
                    if (this.maGrille.listeCases[(k*l)+k].isFixed) {
                        paint.setColor(Color.BLACK);
                    }
                    canvas.drawText(""+this.maGrille.listeCases[(k*l)+k].value,x , y, paint);
                }
            }
         }*/

        for (int l= 0 ; l < 9 ; l++) {

            for (int k= 0 ; k < 9 ; k++) {

                float c1 = (viewWidth/9) *k;
                float l1 = (viewWidth /9) *l;
                float x = (((float)(c0)) / 3 )+ 0 +c1;
                float y = (((float)(l0)) / 3 )+ 25 + l1;

                cpt = (l*9)+k;

                sudokuCase crt = this.maGrille.listeCases[cpt];

                if (crt.value !=0 ) {

                //paint.setColor(Color.BLACK);
                paint.setColor(Color.BLUE);
                if(crt.isFixed) paint.setColor(Color.BLACK);
                canvas.drawText(""+crt.value,x,y,paint);
                //Log.e("  INF0 ", k + " " + l + "\n");
                }
            }
        }


    }

    /*
        Cette méthode permet de dessiner les mask de nombre
        TODO : inspecte le modèle pour ecrire
        Ici on écrit tout les nombres

     */
    private void drawMaskNumber(Canvas canvas) {
        //collonne 1
        float c0 = viewWidth /9;
        float l0 = viewWidth /9;
        int cpt=0;
        Paint paint = new Paint();
        paint.setColor(Color.DKGRAY);
        paint.setTextSize(24);

        Typeface tf = Typeface.create("fontf1.ttf",Typeface.NORMAL);
        paint.setTypeface(tf);

        for (int l= 0 ; l < 9 ; l++) {
            cpt=0;
            for (int k= 0 ; k < 9 ; k++) {
                float c1 = (viewWidth/9) *k;
                float l1 = (viewWidth /9) *l;


                for(int i = 0 ; i <3 ; i ++ ) {

                    for (int j =0 ; j < 3 ; j++) {
                        cpt++;
                        float x = (((float)(j*c0)) / 3 )+ 5 +c1;
                        float y = (((float)(i*l0)) / 3 )+ 20 + l1;
                        canvas.drawText(cpt+"",x , y, paint);
                        // Log.e("  INF0 ", x + " " + y);
                    }
                }
            }
        }

    }


   /*

    */

    //final Handler handler = new Handler();
    Runnable mLongPressed = new Runnable() {
        public void run() {
            Log.i("", "Long press!");
            isDoubleTouch = false;
        }
    };



    boolean isMove = false;
    boolean isDoubleTouch = false;
    int numSelect;
    boolean isCaseSelect = false;
    int xcaseSelect;
    int ycaseSelect;
    public boolean onTouch(View v, MotionEvent event) {
        //handler.removeCallbacks(mLongPressed);
        int x = (int)event.getX();
        int y = (int)event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN :


                handler.postDelayed(mLongPressed, 400);

                if ((y > (viewWidth + 10)) && (y< (viewWidth + 10 + (viewWidth/9)))) {
                    isCaseSelect = true;


                    numSelect = (x / (viewWidth /9)) + 1 ;




                }
                else {
                    xcaseSelect = (x / (viewWidth /9))  ;
                    ycaseSelect = (y / (viewWidth /9))  ;
                    if ( (xcaseSelect < 9 ) && (ycaseSelect < 9) ){
                        if (isDoubleTouch) {
                            Toast.makeText(this.getContext().getApplicationContext(),"delete", Toast.LENGTH_SHORT).show();
                            int n = ((9*(ycaseSelect))+xcaseSelect);

                            if (!(this.maGrille.listeCases[n].isFixed)){
                                this.maGrille.listeCases[n].setPossibleValue(this.maGrille.listeCases[n].value);
                                this.maGrille.listeCases[n].value = 0;
                                this.maGrille.setCasePossibleParCase();
                            }
                        }

                    }

                    isDoubleTouch = true;
                }

                break;
            case MotionEvent.ACTION_MOVE :

                if ( isCaseSelect ) isMove = true;
               // handler.removeCallbacks(mLongPressed);

                break;
            case MotionEvent.ACTION_UP:

              //  handler.removeCallbacks(mLongPressed);
                if (isMove) {
                    xcaseSelect = (x / (viewWidth /9))  ;
                    ycaseSelect = (y / (viewWidth /9))  ;
                   /* AlertDialog alertDialog; //Read Update
                    Activity host = (Activity) this.getContext();
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                           host);


                    builder.setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            });
                    alertDialog = builder.create();
                    alertDialog.setTitle("information");
                    alertDialog.setMessage(""+ numSelect + " " + xcaseSelect + " " + ycaseSelect);

                    alertDialog.show();*/
                    //Log.w("MY MESS2 " , xcaseSelect + "   " + ycaseSelect + " \n "  + this.maGrille.getDescription() );
                    int n = ((9*(ycaseSelect))+xcaseSelect);

                    if (!(this.maGrille.listeCases[n].isFixed)){
                        if (this.maGrille.listeCases[n].asPossibleValeur(numSelect)) {
                            this.maGrille.listeCases[n].value = numSelect;
                            this.maGrille.setCasePossibleParCase();
                        }
                    }
                    Log.w("MY MESS3 " , n + " \n "  + this.maGrille.getDescription() );

                }
                isMove = false;
                isCaseSelect = false;
                break;
        }

        this.invalidate();

        return true;
    }

    /*


     */


    private void drawGrille(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        RectF r = new RectF (0,-1,viewWidth,viewWidth);
        canvas.drawRect(r,paint);
//draw grille

        int b1 = viewWidth /3;
        int b2= b1*2;
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(4);
        //Big line
        canvas.drawLine(b1-2,0,b1-2,viewWidth,paint);
        canvas.drawLine(b2-2,0,b2-2,viewWidth,paint);
        canvas.drawLine(0,b1-2,viewWidth,b1-2,paint);
        canvas.drawLine(0,b2-2,viewWidth,b2-2,paint);

        //small line
        paint.setStrokeWidth(2);
        paint.setColor(Color.DKGRAY);
        int sb =  viewWidth /9;
        canvas.drawLine(sb-1,0,sb-1,viewWidth,paint);
        int sb2 = sb *2;
        canvas.drawLine(sb2,0,sb2,viewWidth,paint);
        sb2 = sb *4;
        canvas.drawLine(sb2,0,sb2,viewWidth,paint);
        sb2 = sb *5;
        canvas.drawLine(sb2,0,sb2,viewWidth,paint);
        sb2 = sb *7;
        canvas.drawLine(sb2,0,sb2,viewWidth,paint);
        sb2 = sb *8;
        canvas.drawLine(sb2,0,sb2,viewWidth,paint);

        canvas.drawLine(0,sb,viewWidth,sb,paint);
        sb2 = sb *2;
        canvas.drawLine(0,sb2,viewWidth,sb2,paint);
        sb2 = sb *4;
        canvas.drawLine(0,sb2,viewWidth,sb2,paint);
        sb2 = sb *5;
        canvas.drawLine(0,sb2,viewWidth,sb2,paint);
        sb2 = sb *7;
        canvas.drawLine(0,sb2,viewWidth,sb2,paint);
        sb2 = sb *8;
        canvas.drawLine(0,sb2,viewWidth,sb2,paint);






    }


    public void running() {
        this.isRunning = true;
        clock = new changementClock(this);
        Thread jthread = new Thread(clock,"moi");
        jthread.start();
        //Activity host = (Activity) this.getContext();
        //host.runOnUiThread(clock);
    }


    public void stopRunning() {
        this.isRunning = false;
    }
    public void resume() {
        this.isRunning = true;
        clock = new changementClock(this);
        Thread jthread = new Thread(clock,"moi");
        jthread.start();
    }
}
class changementClock implements Runnable{

    private final Dessin dessin;

    public changementClock(Dessin dessin) {
        this.dessin = dessin;
    }

    @Override
    public void run() {
        long time= System.currentTimeMillis();
        while (dessin.isRunning){
            long time2= System.currentTimeMillis();
            //Log.e(" thread " , "\n\n MY MESS " + (time2-time));
            this.dessin.time = time2-time;
            try {
                Thread.sleep(1000);
               // dessin.invalidate();
                dessin.handler.sendEmptyMessage(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}